package com.chagee.store.operation.server.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.chagee.base.utils.HttpResponse;
import com.chagee.base.utils.HttpResponseUtil;
import com.chagee.store.operation.api.bo.TagJsonBO;
import com.chagee.store.operation.api.enums.StoreWorkOrderStatusEnum;
import com.chagee.store.operation.api.request.OrderAppealRequest;
import com.chagee.store.operation.api.request.OrderPenalizeMoneyRequest;
import com.chagee.store.operation.api.request.StoreHandleAppealRequest;
import com.chagee.store.operation.api.response.BaiduAiDetectResponse;
import com.chagee.store.operation.api.response.vo.FileVO;
import com.chagee.store.operation.common.constant.CommonConstant;
import com.chagee.store.operation.common.enums.EmailReceiverTypeEnum;
import com.chagee.store.operation.common.enums.EmailTypeEnum;
import com.chagee.store.operation.server.entity.StoreDO;
import com.chagee.store.operation.server.event.service.WorkOrderBaseService;
import com.chagee.store.operation.server.facade.SupplierWorkOrderFacade;
import com.chagee.store.operation.server.feign.SystemApi;
import com.chagee.store.operation.server.feign.UmuApi;
import com.chagee.store.operation.server.model.bo.ExportOrderEmailBO;
import com.chagee.store.operation.server.model.bo.SupplierStatisticsBO;
import com.chagee.store.operation.server.model.bo.WorkOrderDetailBO;
import com.chagee.store.operation.server.model.param.BatchUpdatePenalizeParam;
import com.chagee.store.operation.server.model.param.SupplierTaskExecutionParam;
import com.chagee.store.operation.server.model.response.SupplierTaskDetailResponse;
import com.chagee.store.operation.server.model.vo.BatchUpdatePenalizeVO;
import com.chagee.store.operation.server.service.BaiduAiIdentifyService;
import com.chagee.store.operation.server.service.EmailBizService;
import com.chagee.store.operation.server.service.WorkOrderService;
import com.chagee.store.operation.server.service.base.StoreBaseService;
import com.chagee.store.operation.server.service.biz.WorkOrderAIService;
import com.chagee.store.operation.server.task.NotifySupplierMussedOrderJobHandler;
import com.chagee.store.operation.server.utils.DateUtil;
import com.google.common.collect.Sets;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yhl
 * @version 1.0
 * @className TestController
 * @description test
 * @date 2024/4/23 11:58:40
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

	@Resource
	private BaiduAiIdentifyService baiduAiIdentifyService;

	@Resource
	private WorkOrderAIService workOrderAIService;
	@Resource
	private EmailBizService emailBizService;

	@Resource
	private SupplierWorkOrderFacade supplierWorkOrderFacade;
	@Resource
	private StoreBaseService storeBaseService;

	@Resource
	private WorkOrderService workOrderService;

	@Resource
	private UmuApi umuApi;

	@Value("${template.batchUploadPenalizeMoney}")
	private String batchUploadPenalizeMoneyUrl;

	@PostMapping("/identify/peristalticPump")
	public HttpResponse<List<BaiduAiDetectResponse>> test(@RequestParam String imageUrl) {
		return HttpResponseUtil.success(baiduAiIdentifyService.identifyPeristalticPump(imageUrl));
	}

//	@PostMapping("/ai/peristalticPump")
//	public void aiTest(@RequestBody TaskExecutionDO taskExecutionDO) {
//		workOrderAIService.dealWorkOrderAIPhoto(taskExecutionDO, taskExecutionDO.getAiResultVOList());
//	}

	@PostMapping("/getTaskInfo1")
	public HttpResponse<SupplierTaskDetailResponse> getTaskInfo() {
		SupplierTaskExecutionParam param = new SupplierTaskExecutionParam();
		param.setTaskExecutionId(455L);
		SupplierTaskDetailResponse result = supplierWorkOrderFacade.getTaskInfo(param);
		return HttpResponseUtil.success(result);
	}

	@PostMapping("/orderAppeal1")
	public HttpResponse<Boolean> orderAppeal() {
		OrderAppealRequest request = new OrderAppealRequest();
		request.setWorkOrderNumber("DY202501020053");
		FileVO fileVO = new FileVO("http://uat-chagee20.oss-cn-shanghai.aliyuncs.com/5a1492c3904fe47d474e0fe44b90788e.jpeg", "", 10L, "");
		request.setAppealPic(CollectionUtil.toList(fileVO));
		request.setAppealReason("测试哈");
		return HttpResponseUtil.success(supplierWorkOrderFacade.orderAppeal(request));
	}

	@PostMapping("/penalizeMoney1")
	@ApiOperation("扣除金额")
	public HttpResponse<Boolean> penalizeMoney() {
		OrderPenalizeMoneyRequest request = new OrderPenalizeMoneyRequest();
		request.setPenalizeMoney(new BigDecimal("500"));
		request.setRemark("d发的第三方");
		request.setWorkOrderNumber("DY202501020012");
		return HttpResponseUtil.success(workOrderService.penalizeMoney(request));
	}

	@GetMapping("/batchUpdatePenalizeMoneyTemplate")
	public HttpResponse<String> batchUploadPenalizeMoneyUrlTemplate() {
		if (StringUtils.isNotEmpty(batchUploadPenalizeMoneyUrl)) {
			log.info("batchUploadPenalizeMoneyUrl template {}", JSONUtil.toJsonStr(batchUploadPenalizeMoneyUrl));
			return HttpResponseUtil.success(batchUploadPenalizeMoneyUrl);
		}
		return HttpResponseUtil.success(null);
	}

	@PostMapping("/batchUpdatePenalizeMoney")
	public HttpResponse<BatchUpdatePenalizeVO> batchUpdatePenalizeMoney() {
		BatchUpdatePenalizeParam request = new BatchUpdatePenalizeParam();
		request.setUrl("https://chagee20.oss-cn-shanghai.aliyuncs.com/chagee20/images/20241125/1732533170833/打烊结算模板.xlsx");
		return HttpResponseUtil.success(workOrderService.batchUpdatePenalizeMoney(request));
	}

	@PostMapping("/handleAppeal")
	@ApiOperation("处理申述")
	public HttpResponse<Boolean> handleAppeal() {
		StoreHandleAppealRequest request = new StoreHandleAppealRequest();
		request.setAppealResult("sdsfd");
		request.setIsQualified("Y");
		request.setWorkOrderNumber("DY202501020012");
		return workOrderService.handleAppeal(request);
	}

	@PostMapping("/email")
	public HttpResponse<Boolean> email(@RequestParam String imageUrl) {
		Map<String, Object> hashMap = new HashMap<>();
		hashMap.put("date", DateUtil.yesterdayStr(DateUtil.EMAIL_DATE_PATTERN));
		hashMap.put("supplierName", "测试供应商");
		Map<String, String> emailReceivers = emailBizService.getEmailReceivers(EmailTypeEnum.NOTIFY_SUPPLIER_MISSED_ORDER_OPENING, EmailReceiverTypeEnum.SUPPLIER);

		String supplierEmails = emailReceivers.get("123");

		List<String> list = Arrays.asList(supplierEmails.split(","));

		List<ExportOrderEmailBO> orderEmailBOS = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			ExportOrderEmailBO bo = new ExportOrderEmailBO();
			bo.setStoreNo("34010101" + i);
			bo.setStoreName(UUID.randomUUID().toString());
			bo.setWorkOrderNumber(UUID.randomUUID().toString());
			orderEmailBOS.add(bo);
		}
		byte[] inputStream = EmailBizService.buildExcelBytes(ExportOrderEmailBO.class, orderEmailBOS, null);
		//emailBizService.sendEmail(EmailTypeEnum.NOTIFY_SUPPLIER_MISSED_ORDER_OPENING, list, hashMap, hashMap, hashMap, inputStream);
		return HttpResponseUtil.success(true);
	}

	@PostMapping("/batchQueryStore")
	public HttpResponse<Collection<String>> batchquerystore(@RequestBody List<String> storeNos) {
		List<StoreDO> storeDOS = storeBaseService.batchSelectStoreList(storeNos);
		for (StoreDO storeDO : storeDOS) {
			TagJsonBO tagJsonBO = JSONObject.parseObject(storeDO.getTag(), TagJsonBO.class);
			Set<String> tagCodes = tagJsonBO.getTagCodes();
			if (tagCodes.contains("MDBQ20241220019")){
				System.out.println("true");
			}
		}
		return HttpResponseUtil.success(null);
	}

	@Resource
	private NotifySupplierMussedOrderJobHandler notifySupplierMussedOrderJobHandler;

	@Resource
	private WorkOrderBaseService workOrderBaseService;

	@Value("${supplier.emailStatistics}")
	private String emailStatistics;

	@Resource
	private SystemApi systemApi;

	private final static String city = "{city}：{size}家";

	@PostMapping("/test12")
	public HttpResponse<Collection<String>> batchquerystore1(@RequestBody List<String> storeNos) {
		List<WorkOrderDetailBO> result = new ArrayList<>();
		long startIndex = 0L;
		while (true) {
			List<WorkOrderDetailBO> workOrderDetailBOS = workOrderBaseService.selectOrders(startIndex);
			if (CollectionUtils.isEmpty(workOrderDetailBOS)) {
				break;
			}
			result.addAll(workOrderDetailBOS);
			startIndex = Math.toIntExact(workOrderDetailBOS.stream().map(WorkOrderDetailBO::getId).max(Comparator.naturalOrder()).orElse(0L));
		}
		log.info("推送邮件未接单门店清单 :{}", JSON.toJSONString(result));


		SupplierStatisticsBO supplierStatisticsBO = JSON.parseObject(emailStatistics, new TypeReference<SupplierStatisticsBO>() {
		});
		int boHuiSize = 0;
		int yySySize = 0;
		int shunYaoJiaSize = 0;
		Set<Integer> regionCodeList = Sets.newHashSet();
		List<ExportOrderEmailBO> emailBOList = new ArrayList<>();
		for (WorkOrderDetailBO workOrderDetailBO : result) {
			if (StringUtils.isNotBlank(workOrderDetailBO.getSupplierNo())){
				if (supplierStatisticsBO.getBoHui().contains(workOrderDetailBO.getSupplierNo())) {
					boHuiSize++;
				}
				if (supplierStatisticsBO.getYySy().contains(workOrderDetailBO.getSupplierNo())) {
					yySySize++;
				}
				if (supplierStatisticsBO.getShunYaoJia().contains(workOrderDetailBO.getSupplierNo())) {
					shunYaoJiaSize++;
				}
				String storeRegion = StringUtils.substringBeforeLast(workOrderDetailBO.getRegion(), CommonConstant.OR_STRING);

				ExportOrderEmailBO exportOrderEmailBO = new ExportOrderEmailBO()
					.setStoreNo(workOrderDetailBO.getStoreCode())
					.setStoreName(workOrderDetailBO.getStoreName())
					.setCompanyName(workOrderDetailBO.getCompanyName())
					.setSupplierName(workOrderDetailBO.getSupplier())
					.setWorkOrderNumber(workOrderDetailBO.getWorkOrderNumber())
					.setCreateTime(DateUtil.format(workOrderDetailBO.getCreateTime(), DateUtil.DEFAULT_DATE_TIME_PATTERN))
					.setDocumentStatus(StoreWorkOrderStatusEnum.getByType(workOrderDetailBO.getDocumentStatus()).getDesc())
					.setSupplierNo(workOrderDetailBO.getSupplierNo())
					.setRegion(storeRegion);
				emailBOList.add(exportOrderEmailBO);

				if (StringUtils.isNotBlank(storeRegion)) {
					String[] regionCode = storeRegion.split(CommonConstant.OR_STRING);
					if (regionCode.length > 0) {
						List<Integer> codeList = Arrays.stream(regionCode).map(Integer::parseInt).collect(Collectors.toList());
						regionCodeList.addAll(codeList);
					}
				}
			}
		}

		Map<String, List<ExportOrderEmailBO>> listMap = emailBOList.stream().filter(s -> StringUtils.isNotBlank(s.getSupplierNo())).collect(Collectors.groupingBy(ExportOrderEmailBO::getSupplierNo));


		Map<String, Object> hashMap = new HashMap<>();
		hashMap.put("date", DateUtil.yesterdayStr(DateUtil.EMAIL_DATE_PATTERN));
		hashMap.put("supplierName", "");

		hashMap.put("param1", boHuiSize);
		hashMap.put("param2", yySySize);
		hashMap.put("param3", shunYaoJiaSize);

		//List<ExportOrderEmailBO> collect = listMap.entrySet().stream().map(Map.Entry::getValue).flatMap(List::stream).collect(Collectors.toList());

		String receivers = emailBizService.getReceivers(EmailTypeEnum.NOTIFY_SUPPLIER_MISSED_ORDER_OPENING, EmailReceiverTypeEnum.CLIQUE);
		List<String> list = CollectionUtil.toList(receivers.split(","));

		if (CollectionUtil.isNotEmpty(list) && CollectionUtil.isNotEmpty(emailBOList)) {

			//参数
			notifySupplierMussedOrderJobHandler.builderParam(hashMap, emailBOList, regionCodeList);

			byte[] allInputStream = EmailBizService.buildExcelBytes(ExportOrderEmailBO.class, emailBOList, null);
			try {
				emailBizService.sendEmail(EmailTypeEnum.NOTIFY_SUPPLIER_MISSED_ORDER_OPENING, EmailReceiverTypeEnum.CLIQUE, list, hashMap, hashMap, hashMap, allInputStream);
				log.info("集团项目组人员发送邮件通知成功");
			} catch (Exception e) {
				log.error("集团项目组发送邮件失败通知失败:", e);
			}
		}
		return HttpResponseUtil.success(null);
	}

}
